package com.six.sso.service.impl;

import com.six.core.entity.Emp;
import com.six.core.entity.Permission;
import com.six.sso.feign.EmpFeign;
import com.six.sso.feign.PermissionFeign;
import com.six.sso.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: WangPeng
 * @createTime: 2023/02/27 10:20
 * @description:
 * @version: v1.0
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpFeign empFeign;
    @Autowired
    private PermissionFeign permissionFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户姓名查询用户信息
        Emp emp = empFeign.getByName(username);
        if (emp != null){
            List<Permission> permissionList = permissionFeign.getPermissionByUserId(emp.getId());
            List<SimpleGrantedAuthority> authorityList = permissionList.stream().map(item -> new SimpleGrantedAuthority(item.getCode())).collect(Collectors.toList());
            return new User(username,emp.getPassword(),authorityList);
        }
        return null;
    }
}
